// axios基础的封装
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import router from '@/router'
const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})
// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  //从pinia中获取token
  //通过useUserStore的实例对象userStore获取数据
  const userStore = useUserStore()
  const token = userStore.userInfo.token
  if (token) {
    //2.按照后端要求拼接token数据
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))
// axios响应拦截器
// httpInstance.interceptors.response.use(res => res.data, e => {
//   //统一错误提示
//   ElMessage.warning(e.response.data.message)
//   return Promise.reject(e)
// })
httpInstance.interceptors.response.use(res =>{
  // 判断响应状态码，状态码不是200时，进行错误处理
  if( res.status !== 200 ){
    console.log('response-err:',res.status, res);
    return Promise.reject(new Error('Request failed with status: ' + response.status));
  }
  // 返回数据
  return  res.data
} , error => {
  try{
    // 统一错误提示，判断响应code【由后端返回】
    if( error.response.data.code ){
        // 17001：用户账号密码错误，
        if(error.response.data.code == "17001"){
          ElMessage.error("用户账号或密码错误!")
        }else{
          ElMessage.error(error.response.data.message)
        }
    } else {
      //不存在响应的code
      ElMessage.error("服务器响应失败")
    }
    if( error.response.status === 401 ){
      // 只要接口请求有误：清除本地用户数据，跳转到登录页    
      const userStore = useUserStore()
      userStore.clearUserInfo()
      router.push('/login')
    }
  }catch{
    return Promise.reject(error)
  }
})
export default httpInstance